<template>
  <div class="marketDetails">
    <CustomNavBar>
      <span @click="favoriteStock">
        <i
          v-if="!isFavorite"
          class="iconfont icon icon-shoucang"
          style="color: rgb(94, 243, 200); font-size: 25px"
        ></i>
        <i
          v-else
          class="iconfont icon icon-shoucang1"
          style="color: rgb(94, 243, 200); font-size: 25px"
        ></i>
      </span>
    </CustomNavBar>

    <div class="container">
      <div class="title">{{ querys.name }}</div>
      <!-- <div class="symbol">IHCT.BSE</div> -->
      <div class="new-balance" style="height:1.3rem;">{{ realtimeData.close || '--'}}</div>
      <div class="rate-container">
        <div
          class="rate-item1"
          :class="`${realtimeData.rate < 0 ? 'lower_bg' : 'upper_bg'}`"
        >
          <svg aria-hidden="true" class="icon svg-icon" v-if="realtimeData.rate >= 0">
            <use xlink:href="#icon-up"></use>
          </svg>
          <svg aria-hidden="true" class="icon svg-icon" v-if="realtimeData.rate < 0">
            <use xlink:href="#icon-down"></use>
          </svg>
          <span>{{ realtimeData.rate > 0 ? '+' : '' }}{{realtimeData.rate}}%</span>
        </div>
        <div class="rate-item2" :class="`${realtimeData.balance < 0 ? 'lower' : 'upper'}`">{{ realtimeData.balance }}</div>
      </div>
    </div>

    <div class="tradingview" ref="tradingview">
      <div class="tradingview-info">
        <div class="container">
          <!-- <div class="title" style="color: #000">
            Indian Highway Concessions Trust
          </div>
          <div class="new-balance" style="color: #000; font-size: 0.7rem">
            120.00
          </div> -->
          <!-- <div class="rate-container" style="">
            <div
              class="rate-item1"
              style="
                margin-left: 0;
                font-size: 0.5rem;
                color: #0a9981;
                background: rgb(59, 95, 79, 0);
                font-weight: 600;
              "
            >
              <span>+20.00%</span>
            </div>
            <div
              class="rate-item2"
              style="font-size: 0.5rem; color: #0a9981; font-weight: 600"
            >
              +20.00
            </div>
          </div> -->
          <div class="t-btns">
            <div
              class="t-btn"
              :class="[active == 1 ? 't-btn-active' : '']"
              @click="switchTab(1)"
            >
              1 Y
            </div>
            <div
              class="t-btn"
              :class="[active == 5 ? 't-btn-active' : '']"
              @click="switchTab(5)"
            >
              5 Y
            </div>
            <div
              class="t-btn"
              :class="[active == 10 ? 't-btn-active' : '']"
              @click="switchTab(10)"
            >
              10 Y
            </div>
          </div>
        </div>
      </div>
      <div class="tradingview-container" id="tradingview"></div>
    </div>
    <div class="market-contianer-time">
      <div class="market-contianer-time-name">{{t('Market Depth')}}</div>
      <div class="market-contianer-time-name">({{ formatDate(new Date()) }})</div>
    </div>
    <div class="market-btns">
      <div class="market-btn-buy" @click="buy">{{t('BUY')}}</div>
      <div class="market-btn-sell" @click="goHoldingPage">{{t('SELL')}}</div>
    </div>
    <div class="market-contianer">
      <div class="market-contianer-buy">
        <div class="market-contianer-buy-item">
          <div class="market-contianer-buy-name" style="font-weight: 600">
            {{t('Qty')}}
          </div>
          <div class="market-contianer-buy-value" style="font-weight: 600">
            {{t('Price')}}
          </div>
        </div>
        <div class="market-contianer-buy-item">
          <div class="market-contianer-buy-name" style="font-weight: 600">
            {{t('SELL Qty')}}
          </div>
          <div class="market-contianer-buy-value" style="font-weight: 600">
            {{t('Price')}}
          </div>
        </div>
      </div>
      <div class="market-contianer-buy" v-for="i in 5" :key="i">
        <div class="market-contianer-buy-item">
          <div class="market-contianer-buy-name">{{realtimeData.buy_volume[i] || '--'}}</div>
          <div class="market-contianer-buy-value">{{realtimeData.buy_price[i] || '--'}}</div>
        </div>
        <div class="market-contianer-buy-item">
          <div class="market-contianer-buy-name">{{realtimeData.sell_volume[i] || '--'}}</div>
          <div class="market-contianer-buy-value">{{realtimeData.sell_price[i] || '--'}}</div>
        </div>
      </div>
      <div class="market-contianer-buy">
        <div class="market-contianer-buy-item">
          <div class="market-contianer-buy-name">{{realtimeData.buyQtyTotal || '--'}}</div>
          <div class="market-contianer-buy-value">{{t('Total')}}</div>
        </div>
        <div class="market-contianer-buy-item">
          <div class="market-contianer-buy-name">{{realtimeData.sellQtyTotal || '--'}}</div>
          <div class="market-contianer-buy-value">{{t('Total')}}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { useRouter, useRoute } from "vue-router";
import { Area } from "@antv/g2plot";
// import { Line } from "@antv/g2plot";
import { post, get } from '@/utils/request'
import { onMounted, ref } from "vue";
import { date } from '@/utils/util'
import { closeToast, showLoadingToast,showToast, showSuccessToast, showFailToast  } from 'vant'
import store, { checkExchangeTimeRage } from '@/store/index.js'
import { t } from '@/languages'
const REFRESHTIMER = import.meta.env.VITE_APP_REFRSHTIMER
const router = useRouter();
const querys = useRoute().query
const tradingview = ref(null);
const tradingChart = ref(null)
const active = ref(1);
const isFavorite = ref(false)
let refreshTimer = null
const realtimeData = ref({
  buy_price: [],
  sell_price: [],
  buy_volume: [],
  sell_volume: []
})
const exchangeMap = computed(() => store.exchangeMap)
const thToken = import.meta.env.VITE_APP_THTOKEN
const userDetail = ref({})

function goRecord() {
  router.push("/blockTradingRecordList");
}

function buy() {
  if(userDetail.value.buy_permission !== 1) {
    showToast(t('No permission to purchase at the moment'))
    return
  }
  const excode = exchangeMap.value[querys.ticker].excode
  router.push({
    path: "/buy",
    query: {
      ...querys,
      excode,
    }
  });
}

function switchTab(v) {
  if (active.value == v) return;
  active.value = v;
  getHistoryData()
}

function goHoldingPage() {
  router.push({
    path: '/holdings/index'
  })
}

async function favoriteStock () {
  if(isFavorite.value) {
    showToast(t('Stocks have been collectioned'))
    return
  }
  const res = await post(`/api/app/fstock/`, {
    ticker: querys.ticker
  })
  isFavorite.value = !isFavorite.value
  showSuccessToast(t('Collection successful'))
}

async function getUserInfo() {
  try {
    showLoadingToast()
    const res= await get(`/api/app/getmyinfo/`, {})
    userDetail.value = res
    closeToast()
  } catch (error) {
    showFailToast(error.msg)
  }
}
getUserInfo()
async function checkFavorite() {
  const userInfo = localStorage.getItem('exuserInfo') ? JSON.parse(localStorage.getItem('exuserInfo')) : {}
  try {
    const res = await post('/api/app/fstock/check/', {
      ticker: querys.ticker,
      user_id:userInfo.userId
    }, {
      originResult: true
    })
    isFavorite.value = res.msg === 'true'
  } catch (error) {
    console.log(error)
  }
} 

function getTimeRange () {
  const fullYear = new Date().getFullYear()
  let mounth = new Date().getMonth() + 1
  mounth = mounth > 9 ? mounth : `0${mounth}`
  let day = new Date().getDate()
  day = day > 9 ? day : `0${day}`
  let item = {}
  if(active.value === 1) {
    item.start_date = `${fullYear - 1}-${mounth}-${day}`
  }
  if(active.value === 5) {
    item.start_date = `${fullYear - 5}-${mounth}-${day}`
  }
  if(active.value === 10) {
    item.start_date = `${fullYear - 10}-${mounth}-${day}`
  }
  item.end_date = date(new Date(), 'YYYY-MM-DD')
  return  item
}
const options = {
  data: [],
  xField: "date",
  yField: "close",
  meta: {
    timePeriod: {
      range: [0, 1],
    },
  },
  areaStyle: {
    fill: "l(270) 0:rgba(255,255,255,0) 1:rgba(0,102,82,1)", // 线性渐变，从左到右，红色到粉色的半透明渐变
  },
  color: 'rgb(8,153,129,1)',
  yAxis: {
    position: "right",
  },
  xAxis: {
    grid: {
      line: null,
    },
    tickLine: {
      style: null,
    },
    line: {
      style: {
        stroke: "rgba(255,255,255,0)",
      },
    },
  },
  tooltip: {
    fields: ["date", "close"],
    showTitle: false,
    customContent: (title, items) => {
      if (Array.isArray(items) && items.length > 0) {
        return `<div style="padding:8px;display:flex;justify-content:center;align-items: center;flex-direction: column;">
        <p style="margin-bottom:8px;font-size:16px;font-weight:bold">${
          items[0].data.close
        }</p>
        <p style="margin-bottom:8px;font-size:14px;">${formatDate(
          title
        )}</p>
        </div>`;
      } else {
        return `<div>
        <p>${formatDate(title)}</p>
        </div>`;
      }
    },
  },
}
function initChart() {
  tradingChart.value = new Area("tradingview", options);
  tradingChart.value.render()
}

async function getHistoryData() {
  const d = getTimeRange()
  const stockItem = exchangeMap.value[querys.ticker]
  if(!stockItem) {
    return
  }
  const excode = stockItem.excode
  try {
    
    const url = active.value === 1 ? `/th/fin/stock/${excode}/weekly?` : `/th/fin/stock/${excode}/monthly`
    const res = await get(
    url,
    {
      token: thToken,
      ticker:querys.ticker,
      ...d,
      order: 1,
      columns: `date,close`
    },
  );
  let data = res;
  tradingChart.value.changeData(data);
  } catch (error) {
    
  } finally {
  }
  
}

function formatDate(dateString) {
  const options = { year: "2-digit", month: "short", day: "numeric" };
  const date = new Date(dateString);
  return date.toLocaleDateString("en-US", options);
}

async function getRealtimeData(duration) {
  if(refreshTimer) {
    window.clearTimeout(refreshTimer)
    refreshTimer = null
  }
  refreshTimer = setTimeout(async () => {
    try {
      const stockIem = exchangeMap.value[querys.ticker]
      if(!stockIem) return
      const excode = stockIem.excode
      const res = await get(`/th/fin/stock/${excode}/realtime`, {
        token: thToken,
        ticker: querys.ticker,
        columns:`close,pre_close,buy_price,sell_price,buy_volume,sell_volume`
      })
      const data = res[0] || {}
      const balance = (data.close - data.pre_close).toFixed(2)
      const rate = ((data.close - data.pre_close) / data.pre_close) * 100
      const buy_volume = data.buy_volume || []
      const sell_volume = data.sell_volume || []
      const sellQtyTotal = sell_volume.reduce((a, b) => {
        return a += b
      }, 0)
      const buyQtyTotal = buy_volume.reduce((a, b) => {
        return a += b
      }, 0)
      realtimeData.value = {
        ...data,
        balance: balance > 0 ? `+ ${balance}` : balance,
        rate: rate.toFixed(2),
        buy_price: data.buy_price || [],
        sell_price: data.sell_price || [],
        buy_volume,
        sell_volume,
        buyQtyTotal,
        sellQtyTotal,
      }
    } catch (error) {
      console.log(error)
    }
    if(!checkExchangeTimeRage()) {
      window.clearTimeout(refreshTimer)
      refreshTimer = null
    } else {
      getRealtimeData()
    }
  }, duration || REFRESHTIMER)
  
}

onMounted(() => {
  checkFavorite()
  initChart()
  getRealtimeData(10);
  getHistoryData();
})


onUnmounted(() => {
  window.clearTimeout(refreshTimer)
  refreshTimer = null
})

</script>
<style lang="scss">
.tradingview {
  width: 100%;
  height: 50vh;
  position: relative;
  background-color: #fff;
  .tradingview-info {
    width: 100%;
    height: 20%;
  }
  .tradingview-container {
    width: 100%;
    height: 62%;
    padding: 0.1rem;
  }
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 3;
}

.tradingview-widget-container {
  height: 50vh !important;
}

.marketDetails {
  color: #fff;
  padding-bottom: 0.53333rem;
}

.marketDetails .van-overlay {
  z-index: 2;
}

.marketDetails .van-overlay .wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #ccc;
}

.marketDetails .container {
  padding: 0.53333rem 0.26667rem;
}

.marketDetails .container .title {
  font-size: 0.42667rem;
  font-weight: 700;
}

.marketDetails .container .symbol {
  color: #bfbfbf;
  font-size: 0.32rem;
}

.marketDetails .container .new-balance {
  font-size: 0.96rem;
  font-weight: 800;
  margin-top: 0.12667rem;
  color: #62f792;
}

.marketDetails .container .rate-container {
  display: flex;
}
.t-btns {
  width: 100%;
  margin-top: 0.3rem;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .t-btn {
    padding: 0.2rem;
    border-radius: 0.1rem;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 0.3rem;
    font-weight: 800;
    color: #131722;
    margin-right: 0.3rem;
    font-family: -apple-system, BlinkMacSystemFont, Trebuchet MS, Roboto, Ubuntu,
      sans-serif;
  }
  .t-btn-active {
    background-color: #f0f3fa;
    color: #000;
  }
}

.marketDetails .container .rate-container .rate-item1 {
  white-space: nowrap;
  padding: 0 0.21333rem;
  height: 0.64rem;
  border-radius: 0.10667rem;
  background: hsla(0, 100%, 72%, 0.2);
  margin-right: 0.21333rem;
  font-size: 0.32rem;
  font-weight: 500;
  margin-left: 0.05333rem;
  display: flex;
  align-items: center;
}

.marketDetails .container .rate-container .rate-item1 .icon {
  width: 0.53333rem;
  height: 0.53333rem;
}

.marketDetails .container .rate-container .rate-item2 {
  font-size: 0.32rem;
  font-weight: 500;
  margin-left: 0.05333rem;
  display: flex;
  align-items: center;
}

.marketDetails .market-btns {
  padding: 0 0.26667rem;
  display: grid;
  grid-template-columns: 1fr 1fr;
  column-gap: 0.26667rem;
}

.marketDetails .market-btns .market-btn-buy {
  text-align: center;
  font-weight: 600;
  padding: 0.32rem 0.53333rem;
  border-radius: 0.66667rem;
  color: #0d111a;
  background: linear-gradient(270deg, #d02f5e, #fed053);
}

.marketDetails .market-btns .market-btn-sell {
  text-align: center;
  font-weight: 600;
  color: #0d111a;
  background: linear-gradient(270deg, #62f792, #63fddb);
  padding: 0.32rem 0.53333rem;
  border-radius: 0.66667rem;
}

.marketDetails .kilne-des {
  padding: 0.26667rem 0;
  padding-left: 0.26667rem;
  background-color: #fff;
  color: #d44d4f;
}

.marketDetails .k-line-container .tab-container .tabs .van-tabs__nav {
  background-color: unset;
}

.marketDetails .k-line-container .tab-container .tabs .van-tabs__nav .van-tab {
  color: #fff;
  flex: none;
  padding: 0 0.4rem;
}

.marketDetails
  .k-line-container
  .tab-container
  .tabs
  .van-tabs__nav
  .van-tabs__line {
  width: 0.8rem;
}

.marketDetails
  .k-line-container
  .tab-container
  .tabs
  .van-tabs__nav
  .van-tab--active {
  color: #7fdf9a !important;
}

.marketDetails .k-line-container #kline {
  width: 100%;
  height: 10.66667rem;
}

.market-contianer {
  margin: 0 0.26667rem;
  box-shadow: 0 0.10667rem 0.37333rem 0 rgba(0, 0, 0, 0.25);
  margin-top: 0.4rem;
  border-radius: 0.13333rem;
}

.market-contianer .market-contianer-buy {
  display: flex;
  width: 100%;
  .market-contianer-buy-item {
    flex: 1;
    display: flex;
    padding: 0.26667rem 0;
  }
}




.marketDetails
  .market-contianer
  .market-contianer-buy
  .market-contianer-buy-item
  .market-contianer-buy-name {
  flex: 1;
  color: #fff;
  font-size: 0.37333rem;
  padding-left: 0.13333rem;
}

.marketDetails
  .market-contianer
  .market-contianer-buy
  .market-contianer-buy-item
  .market-contianer-buy-value {
  flex: 1;
  color: #fff;
  font-size: 0.37333rem;
  text-align: right;
  padding-right: 0.13333rem;
}

.marketDetails .market-contianer-time {
  display: flex;
  padding: 0.26667rem;
  margin-top: 0.26667rem;
}

.marketDetails .market-contianer-time div {
  flex: 1;
  color: #fff;
}

.marketDetails .sell-cell {
  border-bottom: 0.02667rem solid #e0e0e0;
  margin-bottom: 0.26667rem;
  height: 8rem;
  overflow-y: auto;
}

.marketDetails .sell-cell .cell-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.13333rem;
}

.marketDetails .sell-cell .cell-item .cell-item-name {
  font-size: 0.37333rem;
}

.marketDetails .sell-cell .cell-item .cell-item-name .cell-item-name-last {
  color: #d73d3d;
  font-size: 0.42667rem;
}

.marketDetails .sell-cell .cell-item .cell-item-name .cell-item-name-top {
  color: #333;
  font-size: 14;
  font-weight: 600;
}

.marketDetails .sell-cell .cell-item .cell-item-name .cell-item-name-bottom {
  margin-top: 0.13333rem;
  width: auto;
  padding: 0 0.08rem;
  background: rgba(59, 79, 222, 0.1);
  border-radius: 0.05333rem;
  color: #3b4fde;
  font-size: 0.32rem;
  vertical-align: middle;
}

.marketDetails .sell-cell .cell-item .cell-item-name-sufix {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.marketDetails .sell-cell .cell-item .cell-item-value {
  font-size: 0.37333rem;
}

.marketDetails .sell-cell .cell-item .cell-item-value .cell-item-value-box {
  background: linear-gradient(90deg, #4b9dd6, #2f38d5);
  border-radius: 0.26667rem;
  text-align: center;
  color: #fff;
  font-size: 0.37333rem;
  padding: 0.05333rem 0.4rem;
}

.marketDetails .sell-cell .cell-item-rows {
  display: flex;
}

.marketDetails .sell-cell .cell-item-rows .cell-item-row {
  display: flex;
  flex: 1;
  height: 0.66667rem;
  line-height: 0.66667rem;
  font-size: 0.37333rem;
}

.marketDetails
  .sell-cell
  .cell-item-rows
  .cell-item-row
  .cell-item-rows-name-padding {
  padding-left: 0.26667rem;
}

.marketDetails .sell-cell .cell-item-rows .cell-item-row .cell-item-rows-value {
  flex: 1;
  text-align: right;
  color: #d73d3d;
}
</style>
